package cn.itcast.service;


import cn.itcast.pojo.Permission;
import cn.itcast.pojo.Role;
import cn.itcast.pojo.User;
import com.alibaba.dubbo.config.annotation.Reference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;

    //密码加密的对象
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 根据用户名查询各种信息
     *
     * @param userName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        log.debug("登录的用户名:{}", userName);
        //远程调用查询用户信息
        User user = userService.userLogin(userName);
        if (user == null){
            return null;
        }
        log.debug("查询出的用户信息:{}", user);

        //创建集合保存
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        //得到该用户的角色
        Set<Role> roles = user.getRoles();
        log.debug("查询出的用户的角色信息:{}",roles);

        //遍历用户角色的集合
        for (Role role : roles) {
            //设置当前用户的角色
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getKeyword()));  //ROLE_XXXXX

            //获取该角色所有的权限集合
            Set<Permission> permissions = role.getPermissions();
            log.debug("查询出的用户的权限信息:{}",permissions);

            //遍历给用户赋予权限,一个角色拥有多个权限
            for (Permission permission : permissions) {
                grantedAuthorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //返回给框架规定的user对象,如果密码不需要加密的话在添加密码前拼接一个"{noop}"字符串
        return new org.springframework.security.core.userdetails.User(userName, user.getPassword(), grantedAuthorities);
    }
}
